package main

import (
	"github.com/gomodule/redigo/redis"
	"log"
	"time"
)

/*
	1. 创建连接池
	2. 简单设置连接池的最大链接数等参数
	3. 注入拨号函数（设置redis地址 端口号等）
	4. 调用pool.Get() 获取连接
	5. 使用连接Do函数请求redis
	6. 关闭连接
*/

//创建了一个全局变量用于存储redis的连接池 避免每次调用方法都去创建耗费时间
var p = redis.NewPool(newFn, 10)

func main() {
	reply, err := doSetExec("name1", "fang")
	if err != nil {
		log.Println(err)
	}
	log.Println(reply)
	reply2, err2 := doQuery("name1")
	if err2 != nil {
		log.Println(err2)
	}
	log.Println(reply2)

	p.Close()
}
func doQuery(value string) (reply string, err error) {
	c := p.Get()
	defer c.Close()
	reply = "fail!"
	reply, err = redis.String(c.Do("get", value))
	if err != nil {
		return
	}
	return

}
func doSetExec(key string, value string) (reply string, err error) {
	c := p.Get()
	defer c.Close()
	_, err = c.Do("set", key, value)
	reply = "fail!"
	if err != nil {
		return
	}
	reply = "succeed"
	return

}

func newFn() (redis.Conn, error) {
	var (
		timeout      time.Duration
		readTimeOut  time.Duration
		writeTimeOut time.Duration
	)
	timeout = 5 * time.Second
	readTimeOut = 5 * time.Second
	writeTimeOut = 5 * time.Second

	return redis.Dial("tcp",
		"81.68.186.20:6379",
		redis.DialDatabase(0),
		redis.DialPassword("ffdd2021@"),
		redis.DialConnectTimeout(timeout),
		redis.DialReadTimeout(readTimeOut),
		redis.DialWriteTimeout(writeTimeOut))

}
